#include "bridgeHandle.h"
#include "utils.h"
#ifdef _WIN32
#include <shlobj.h>
#endif
bridgeHandle::bridgeHandle()
{
	char path[1000] = { 0 };
#ifdef _WIN32
	SHGetSpecialFolderPath(NULL, path, CSIDL_PROFILE, FALSE);
	strcat(path, "/AppData/Local/Linkdood/log/bridge.log");
#else
	strcat(path, getenv("HOME"));
	strcat(path, "/.local/share/Linkdood/log/bridge.log");
#endif
	hlog_set_file(path);
	hlog_set_level(LOG_LEVEL_WARN);
	hlogd("bridgeHandle::bridgeHandle");
}

bridgeHandle::~bridgeHandle()
{

}

int bridgeHandle::send(const char *json)
{
	std::string typeName = "";

	if (bridge_name.find("linkdood") != std::string::npos) {
		typeName = "linkdood";
	}
	else {
		
		typeName = "thirdParty";
	}
	int code = -1;
#ifdef _WIN32
	code = SendCmdToScreenShotProcess((char*)typeName.c_str(),json);
#else
	code = send_a_signal((char*)typeName.c_str(),json);
#endif // _WIN32
	return code;
}

void bridgeHandle::Init(const char * initData)
{
	std::string data(initData);
	bridge_name = initData;
	
#ifdef _WIN32
	InitSharedMemory(data);
	Sleep(300);
#endif // _WIN32
	
}

int bridgeHandle::regReceiveCallback(std::function<void(char*)>cb) {
	std::string typeName = "";
	
	if (bridge_name.find("linkdood") != std::string::npos) {
		typeName = "linkdood";
	}
	else {
		typeName = "thirdParty";
	}
#ifdef _WIN32
	ReceiveCmdFromScreenShot((char*)typeName.c_str(),cb);
#else
	listen_signal((char*)typeName.c_str(),cb);
#endif // _WIN32
	return 0;
}
void bridgeHandle::Uninit()
{
#ifdef _WIN32
	UnInitSharedMemory();
#endif // _WIN32
}
std::string generate()
{
#if defined(_WIN32)
	char buf[GUID_LEN] = { 0 };
	GUID guid;

	if (CoCreateGuid(&guid))
	{
		return std::move(std::string(""));
	}

	sprintf_s(buf,
		"%02X-%02X-%02X-%02X-%02X-%02X",
		guid.Data4[0], guid.Data4[1], guid.Data4[2],
		guid.Data4[3], guid.Data4[4], guid.Data4[5]);

	return std::move(std::string(buf));
#elif defined(__linux__)
	char buf[GUID_LEN] = { 0 };

	uuid_t uu;
	uuid_generate(uu);
	uuid_unparse(uu, buf);

	return std::move(std::string(buf));
#endif
}
